<template>
    <yh-dialog :title="title" width="800px" :visible.sync="visibleTemp" :close-on-click-modal="false" drag>
        <div class="dialog-main-body" v-loading="loading">
            <div class="dialog-main-body-box">
                <div class="dialog-main-body-box-hd">未选部分</div>
                <draggable
                    class="dialog-main-body-box-content right-content"
                    v-model="noneSelected"
                    group="box"
                    animation="300"
                    :key="noneSelected.length"
                >
                    <transition-group class="dialog-box-group">
                        <div class="dialog-box-group-item" v-for="item in noneSelected" :key="item.field + item.title">{{ item.title }}</div>
                    </transition-group>
                </draggable>
            </div>
            <div class="dialog-main-body-box">
                <div class="dialog-main-body-box-hd">已选部分</div>
                <div class="dialog-main-body-box-fixed" v-if="fixedColumns.length">
                    <div class="dialog-box-group-item is-disabled" v-for="item in fixedColumns" :key="item.field + item.title">
                        {{ item.title }}
                    </div>
                </div>
                <draggable class="dialog-main-body-box-content" v-model="selected" group="box" animation="300" :key="selected.length">
                    <transition-group class="dialog-box-group">
                        <div class="dialog-box-group-item" v-for="item in selected" :key="item.field + item.title">
                            {{ item.title }}
                        </div>
                    </transition-group>
                </draggable>
            </div>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="reset">重置</el-button>
            <el-button size="mini" @click="visibleTemp = false">取 消</el-button>
            <el-button size="mini" type="primary" @click="onSubmit" v-loading="loading">确 定</el-button>
        </div>
    </yh-dialog>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch, Emit } from 'vue-property-decorator';
import draggable from 'vuedraggable';
import { ColumnVO } from '@/common/vo';
import { getTableLayout2, updateTableLayout } from '@/common/api/commonApi';
import { Col } from 'element-ui';

@Component({ name: 'RiskTableLayout', components: { draggable } })
export default class RiskTableLayout extends Vue {
    @Prop({ default: '页面布局' }) readonly title?: string;
    @Prop({ default: false }) readonly visible!: boolean;
    @Prop({ required: true }) readonly tableName!: string;
    @Prop({ default: () => [] }) readonly column!: ColumnVO[];
    @Prop({ default: () => [] }) readonly fixedColumns!: ColumnVO[]; // 固定选择列
    @Prop({ default: () => [] }) readonly resetNoSelectedFieldList: ColumnVO[]; // 重置时未选列

    visibleTemp: boolean = false;
    loading: boolean = false;
    columns: ColumnVO[] = [];
    defaultSelected: ColumnVO[] = [];
    showColumns: ColumnVO[] = []; // 父组件最终展示的列
    selected: ColumnVO[] = [];
    noneSelected: ColumnVO[] = [];

    async mounted() {
        await this.getDefaultSelected();
    }

    @Watch('visible')
    onWatchVisible(value: boolean) {
        this.visibleTemp = value;
        if (value) {
            this.filterList(this.columns, this.defaultSelected, this.fixedColumns);
        }
    }

    @Watch('visibleTemp')
    onWatchVisibleTemp(value: boolean) {
        if (value !== this.visible) {
            this.$emit('update:visible', value);
        }
    }

    @Watch('column', { immediate: true, deep: true })
    watchcolumn(newData, oldData) {
        // 过滤掉勾选框
        this.columns = newData.filter(i => i.field);
    }

    /**
     * 获取表格布局
     */
    async getDefaultSelected() {
        let nokeys = this.resetNoSelectedFieldList.map(item => item.field);
        let newUserParams = this.columns.filter(item => !nokeys.includes(item.field));
        let res = (await getTableLayout2(this.tableName)) || newUserParams;

        // 旧数据兼容
        res.forEach(element => {
            element.field = element.id || element.field;
            element.title = element.content || element.title;
        });
        this.defaultSelected = res || [];
        this.selected = res || [];
        this.packageColumns();
    }

    /**
     * 过滤数据
     * @param allList 表格全部字段
     * @param selectedList 表格已选择字段
     * @param fixedList 表格固定字段
     */
    filterList(allList: ColumnVO[], selectedList: ColumnVO[], fixedList: ColumnVO[]): void {
        // 1. 获取固定 keys
        const fixedKeys = fixedList.map(item => item.field);
        // 2. 剔除固定值，获取全部列表
        const all = allList.filter(item => {
            return !fixedKeys.includes(item.field);
        });
        // 3. 获取已选择的列表
        const selected = selectedList.filter(selectedItem => {
            const value = all.find(allItem => {
                return allItem.field === selectedItem.field;
            });
            return !!value;
        });
        // 4. 获取未选择的列表
        const noneSelected = all.filter(allItem => {
            const value = selectedList.find(selectedItem => {
                return allItem.field === selectedItem.field;
            });
            return !value;
        });
        this.selected = selected;
        this.noneSelected = noneSelected;
    }

    /**
     * 重置按钮事件
     */
    reset() {
        // 1. 获取固定 keys
        const fixedKeys = this.fixedColumns.concat(this.resetNoSelectedFieldList).map(item => item.field);

        // 2. 剔除固定值，获取全部列表
        this.selected = this.columns.filter(item => {
            return !fixedKeys.includes(item.field);
        });
        // this.selected = JSON.parse(JSON.stringify([...this.selected, ...this.noneSelected]));

        this.noneSelected = this.resetNoSelectedFieldList;
    }

    /**
     * 确认按钮事件
     */
    onSubmit() {
        const data = {
            showField: JSON.stringify(this.selected),
            tableName: this.tableName,
        };
        this.loading = true;
        updateTableLayout(data)
            .then(async () => {
                await this.getDefaultSelected();
                this.visibleTemp = false;
                this.yh_message_success('修改成功');
            })
            .finally(() => {
                this.loading = false;
            });
    }

    /**
     * 将[{ field:xx, title: xx }] 转换为 [{ field:xx, title:xx, width:xx, render:xx }]
     */
    packageColumns(): void {
        //  固定列keys
        const fixedKeys = this.fixedColumns.map(i => i.field);
        // 已选择keys
        const selectedKeys = this.selected.map(i => i.field);
        // 展示列keys
        const showColKeys = [...new Set([...fixedKeys, ...selectedKeys])];

        let showColumns = [];
        // 先添加check或者expand
        showColumns = [...this.column.filter(i => !i.field)];
        // 再按照展示列顺序插入
        showColKeys.forEach(element => {
            let data = this.column.find(o => o.field === element);
            if (data) {
                showColumns.push(data);
            }
        });

        // this.column.forEach((i) => {
        //     if (!i.field || showColKeys.includes(i.field)) {
        //         showColumns.push(i);
        //     }
        // });

        this.showColumns = showColumns;
    }

    // 开始拖拽事件
    onStart() {
        // this.drag = true;
    }
    // 拖拽结束事件
    onEnd() {
        // this.drag = false;
    }
}
</script>

<style lang="scss" scoped>
.dialog-main-body {
    height: 345px;
    display: flex;
    justify-content: space-between;

    .dialog-main-body-box {
        display: flex;
        flex-direction: column;
        width: calc(50% - 10px);
        height: 100%;
        border: 1px solid #cacaca;
        border-radius: 2px;

        .dialog-main-body-box-hd {
            height: 30px;
            padding: 0 5px;
            font-size: 14px;
            font-weight: bold;
            line-height: 30px;
            color: rgba(0, 0, 0, 0.65);
        }

        .dialog-main-body-box-fixed {
            width: 100%;
            padding: 0 3px;
            border-top: 1px solid #cacaca;
        }

        & /deep/ {
            .dialog-main-body-box-content {
                flex-grow: 1;
                height: 0;
                width: 100%;
                padding: 0 5px 5px 5px;
                border-top: 1px solid #cacaca;

                .dialog-box-group {
                    display: block;
                    width: 100%;
                    height: 100%;
                    overflow-x: hidden;
                    overflow-y: auto;
                }
            }

            .dialog-box-group-item {
                display: inline-block;
                margin: 3px;
                height: 30px;
                padding: 0 10px;
                border: 1px dashed #409eff;
                border-radius: 3px;
                line-height: 28px;
                color: rgb(102, 102, 102);
                background-color: #fff;
                cursor: move;
                user-select: none;

                &.is-disabled {
                    background-color: rgb(230, 230, 230);
                    cursor: no-drop;
                }
            }
        }
    }
}

/deep/ .el-dialog .el-dialog__body {
    max-height: none;
}
</style>
